package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.ProjectManagementListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityProjectManagementBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppProjectModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

/**
 * 项目管理
 */
public class ProjectManagementActivity extends BaseActivity implements ProjectManagementListViewAdapter.ProjectManagementListItemClickListener, BaseListener {
    private ActivityProjectManagementBinding binding;
    private Context mContext;
    private ProjectManagementListViewAdapter listViewAdapter;
    private int pageNo = 1, pageSize = 10;
    private Handler mHandler = new Handler();
    private SearchView searchView;
    private MenuItem searchMenu;
    private String cx_projecttype;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_project_management);
        setActionBar(true, "项目列表");
        mContext = this;

        listViewAdapter = new ProjectManagementListViewAdapter(mContext);
        binding.listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemClickListener(this);

        binding.ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(getString(R.string.no_network));
                    return;
                }
                query();
            }
        });

        binding.ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(getString(R.string.no_network));
                    return;
                }
                queryMore();
            }
        });
        binding.ptrClassicFrameLayout.disableWhenHorizontalMove(true);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.ptrClassicFrameLayout.autoRefresh();
            }
        }, 32);
    }

    private void query() {
        listViewAdapter.clear();
        pageNo = 1;
        JSONObject param = new JSONObject();
        param.put("AreaID", AppLoginModel.getAreaId(mContext));
        param.put("name", searchView == null ? null : searchView.getQuery().toString());
        param.put("endtime", "");
        param.put("cx_projectstep", "");
        param.put("cx_projecttype", StringUtil.getValue(cx_projecttype));
        param.put("pageIndex", pageNo);
        param.put("pagesize", pageSize);
        AppProjectModel.GetProjects(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                JSONArray array = JSON.parseArray(val);
                binding.ptrClassicFrameLayout.setLoadMoreEnable(!(array.size() < pageSize));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                showMsg(error);
            }
        });
    }

    private void queryMore() {
        pageNo += 1;
        JSONObject param = new JSONObject();
        param.put("AreaID", AppLoginModel.getAreaId(mContext));
        param.put("name", searchView == null ? "" : searchView.getQuery().toString());
        param.put("endtime", "");
        param.put("cx_projectstep", "");
        param.put("cx_projecttype", StringUtil.getValue(cx_projecttype));
        param.put("pageIndex", pageNo);
        param.put("pagesize", pageSize);
        AppProjectModel.GetProjects(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONArray array = JSON.parseArray(val);
                binding.ptrClassicFrameLayout.loadMoreComplete(!(array.size() < pageSize));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.loadMoreComplete(false);
                showMsg(error);
            }
        });
    }

    private void setSearchView() {
        if (this.searchView != null) {
            EditText searchPlate = (EditText) this.searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
            if (searchPlate == null)
                return;
            searchPlate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        binding.ptrClassicFrameLayout.autoRefresh();
                    }
                    return false;
                }
            });
        }
    }

    private void hideSearchView() {
        if (this.searchMenu != null)
            this.searchMenu.collapseActionView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (menu != null)
            menu.clear();
        getMenuInflater().inflate(R.menu.project_menu, menu);
        MenuItem action = menu.findItem(R.id.action_menu);
        SubMenu subMenu = action.getSubMenu();
        JSONArray menus = AppProjectModel.getProjectType(mContext);
        if (menus != null) {
            for (int i = 0, j = menus.size(); i < j; i++) {
                JSONObject b = menus.getJSONObject(i);
                MenuItem menuItem = subMenu.add(b.getString("NAME"));
                Intent intent = new Intent();
                intent.putExtra("data", b.toString());
                menuItem.setIntent(intent);
            }
        } else {
            AppProjectModel.GetProjectType(mContext, null, this);
        }

        searchMenu = menu.findItem(R.id.action_search);
        searchView = (SearchView) searchMenu.getActionView();
        setSearchView();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        hideSearchView();
        switch (item.getItemId()) {
            case R.id.btn_all:
                cx_projecttype = null;
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            default: {
                Intent intent = item.getIntent();
                if (intent == null)
                    break;
                String data = intent.getStringExtra("data");
                JSONObject $data = JSON.parseObject(data);
                cx_projecttype = StringUtil.dTs($data.getString("ID"));
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            }
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onItemClick(int position) {
        if (!NetWorkUtils.isNetworkConnected(mContext)) {
            showMsg(getString(R.string.no_network));
            return;
        }
        JSONObject item = (JSONObject) listViewAdapter.getItem(position);
        Bundle bundle = new Bundle();
        bundle.putString(DefaultModel.PAGE_DATA_ID, StringUtil.dTs(item.getString("ID")));
        bundle.putString(DefaultModel.PAGE_NAME, item.getString("NAME"));
        toActivity(ProjectDetailActivity.class, bundle);
    }

    @Override
    public void success(String val, String action) {
        invalidateOptionsMenu();
    }

    @Override
    public void error(String error, String action) {

    }
}
